package com.os.opencv.java.chapter9;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class BoundingRect {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/erzhi.jpg", Imgcodecs.IMREAD_GRAYSCALE);

        Mat binary = new Mat();
        Imgproc.threshold(src, binary, 90, 255, Imgproc.THRESH_BINARY);
        HighGui.imshow("binary", binary);
        HighGui.waitKey(0);

        //根据二值图检测轮廓
        List<MatOfPoint> contour = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(binary, contour, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

        //在图像上绘制各个轮廓的边界矩形
        src = Imgcodecs.imread("/Users/matt/Pictures/erzhi.jpg");
        for(int i=0; i<contour.size(); i++){
            Rect rect = Imgproc.boundingRect(contour.get(i));
            Imgproc.rectangle(src, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0,0,255),3);
        }

        //在屏幕上绘制有直边界矩形的图像
        HighGui.imshow("rect", src);
        HighGui.waitKey(0);

        System.exit(0);

    }
}
